<template>

  <el-dialog
    title="选择部门/角色/人员"
    :visible.sync="selectAllDialogVisible"
    width="50%"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <el-container>
      <el-tabs
        v-if="selectAllDialogVisible"
        v-model="selectActiveName"
        @tab-click="handleClick"
      >
        <!-- 选择部门 -->
        <el-tab-pane
          v-if="departmentshow"
          label="部门"
          name="first"
        >
          <el-input
            v-model="departmentName"
            placeholder="搜索部门"
            class="input-with-select"
            style="margin: 5px auto"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
            />
          </el-input>
          <el-main style="padding: 10px 0">
            <el-row>
              <el-col
                :span="24"
                class="departList"
              >
                <el-container>
                  <el-main>
                    <div class="my-list table-tree">
                      <el-tree
                        ref="treeref"
                        :data="department"
                        :props="departprops"
                        show-checkbox
                        :check-strictly="true"
                        node-key="Id"
                        :default-expand-all="true"
                        :expand-on-click-node="false"
                        :check-on-click-node="true"
                        :filter-node-method="filterNode"
                        @check-change="checkdepartmentchoose"
                      />
                    </div>
                  </el-main>
                </el-container>
              </el-col>
            </el-row>
          </el-main>
        </el-tab-pane>

        <!-- 选择角色 -->
        <el-tab-pane
          v-if="roleshow"
          label="角色"
          name="second"
        >
          <el-input
            v-model="RoleName"
            placeholder="搜索角色"
            class="input-with-select"
            style="margin: 5px auto"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
            />
          </el-input>
          <el-main style="padding: 10px 0">
            <el-row>
              <el-col
                :span="24"
                class="departList"
              >
                <el-container>
                  <el-main>
                    <el-table
                      ref="roleref"
                      :data="roles"
                      :border="false"
                      style="width: 100%"
                      @row-click="handleRoleRow"
                      @select="handleRoleSelect"
                      @select-all="handleRoleSelectAll"
                    >
                      <el-table-column
                        type="selection"
                        width="90"
                      />
                      <el-table-column
                        prop="Name"
                        label="全选"
                        width=""
                      />
                    </el-table>
                  </el-main>
                </el-container>
              </el-col>
            </el-row>
          </el-main>
        </el-tab-pane>
        <!-- 选择人员 -->
        <el-tab-pane
          v-if="personshow"
          label="人员"
          name="third"
        >
          <el-input
            v-model="searchPersonContent"
            placeholder="搜索员工"
            class="input-with-select"
            style="margin: 5px auto"
            @keyup.enter.native="personfillter"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
            />
          </el-input>

          <el-main style="padding: 10px 0">
            <el-row>
              <el-col
                :span="12"
                class="departList"
              >
                <el-container>
                  <el-main>
                    <div class="my-list table-tree">
                      <el-tree
                        :data="department"
                        :props="departprops"
                        :default-expand-all="true"
                        @node-click="handleNodePersonClick"
                      />
                    </div>
                  </el-main>
                </el-container>
              </el-col>
              <el-col
                :span="12"
                style="padding-left: 10px"
              >
                <el-row>
                  <el-col
                    :span="24"
                    class="departList"
                  >
                    <el-container>
                      <el-main>
                        <el-table
                          ref="personref"
                          :data="tableData"
                          :border="false"
                          style="width: 100%"
                          @row-click="handleRow"
                          @select="handleSelect"
                          @select-all="handleSelectAll"
                        >
                          <el-table-column
                            prop="Name"
                            label="全选"
                            width=""
                          />
                          <el-table-column
                            type="selection"
                            width="90"
                          />
                        </el-table>
                      </el-main>
                    </el-container>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-main>
        </el-tab-pane>
      </el-tabs>

      <el-main class="select-person">
        <el-row
          type="flex"
          style="flex-wrap: wrap"
        >
          <el-tag
            v-for="tag in tags"
            :key="tag.Id"
            closable
            :type="
              tag.Type === 1
                ? tagType.warning
                : tag.Type === 2
                  ? tagType.success
                  : tagType.danger
            "
            style="margin: 10px"
            @close="handleClose(tag)"
          >
            {{ tag.Name }}
          </el-tag>
        </el-row>
      </el-main>
      <el-footer>

        <div>
          <el-button
            size="medium"
            @click="onCancel"
          >返回</el-button>
          <el-button
            type="primary"
            size="medium"
            @click="onSubmit"
          >提交</el-button>
        </div>
      </el-footer>
    </el-container>
  </el-dialog>

</template>
<script>
import { getDepartment } from '@/api/department/department'
import { getUnitRoles } from '@/api/sysrole/sysrole'
import {
  GetUserByOrgId,
  GetUserByName
} from '@/api/user/user'
import { deepClone } from '@/utils/index'
export default {
  props: {
    echoList: {
      type: Array,
      default: () => {
        return []
      }
    },
    departmentshow: {
      type: Boolean,
      default: true
    },
    roleshow: {
      type: Boolean,
      default: true
    },
    personshow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      departprops: {
        value: 'Id', // ID字段名
        label: 'OrgName', // 显示名称de
        children: 'Children' // 子级字段名
      },
      deaprops: {
        value: 'Id', // ID字段名
        label: 'Name', // 显示名称de
        children: 'children' // 子级字段名
      },
      tagType: { success: 'success', warning: 'warning', danger: 'danger' }, // tag显示类型
      selectAllDialogVisible: false, // 弹窗
      searchPersonContent: '', // 人员名称
      departmentName: '', // 部门名称
      RoleName: '', // 角色名称
      selectActiveName: 'first',
      tableData: [], // table数据
      department: [], // 部门树形数据
      roles: [], // 角色数据
      tags: [],
      selectArr: []
    }
  },
  watch: {
    departmentName(val) {
      this.$refs.treeref.filter(val)
    },
    RoleName(val) {
      this.$refs.roletreeref.filter(val)
    }
  },
  created() {},
  methods: {
    onCancel() {
      this.selectAllDialogVisible = false
      this.tags = []
    },
    onSubmit() {
      this.selectAllDialogVisible = false
      this.$emit('allSelect', this.tags)
    },
    /** ****人员 ******/
    handleRow(row) {
      this.$refs.personref.toggleRowSelection(row)
      // var ischeck = this.selectArr.indexOf(row) > -1 // 是否选中
      var ischecked = false // 是否已选择
      this.tags.forEach(item => {
        if (item.Id === row.Id) {
          ischecked = true
          this.tags.splice(this.tags.indexOf(item), 1)
          // if (!ischeck) {
          //   // 取消选中
          //   this.tags.splice(this.tags.indexOf(item), 1)
          // }
        }
      })
      if (!ischecked) {
        // 全选 && 未被选择  添加当前项
        this.tags.push(row)
      }
    },
    handleSelectChange(val) {
      this.selectArr = val
    },
    // 获取部门数据
    getdepartment() {
      var _this = this
      getDepartment().then(res => {
        _this.department = res.Data
      })
    },
    // 通过部门id获取人员列表
    getuserlist(departId) {
      GetUserByOrgId(departId).then(res => {
        this.tableData = res.Data
        this.setChecked()
      })
    },

    // table回显
    setChecked() {
      this.$nextTick(() => {
        if (this.tags.length > 0 && this.tableData.length > 0) {
          this.tableData.forEach(item => {
            var ischeck = false
            this.tags.forEach(citem => {
              if (item.Id === citem.Id) {
                ischeck = true
              }
            })
            this.$refs.personref.toggleRowSelection(item, ischeck)
          })
        }
      })
    },
    // 移除tag
    handleClose(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1)
      // 根据数据类型分别删除1-部门2-人员3-角色
      if (tag.Type === 1) {
        this.$refs.treeref.setCheckedNodes(this.tags)
      }
      if (tag.Type === 2) {
        this.tableData.forEach((item, index) => {
          if (tag.Id === item.Id) {
            this.$refs.personref.toggleRowSelection(
              this.tableData[index],
              false
            )
          }
        })
      }
      if (tag.Type === 3) {
        this.roles.forEach((item, index) => {
          if (tag.Id === item.Id) {
            this.$refs.roleref.toggleRowSelection(
              this.roles[index],
              false
            )
          }
        })
      }
    },
    // 选择table某一行
    handleSelect(selection, row) {
      var ischeck = selection.indexOf(row) > -1 // 是否选中
      var ischecked = false // 是否已选择
      this.tags.forEach(item => {
        if (item.Id === row.Id) {
          ischecked = true
          if (!ischeck) {
            // 取消选中
            this.tags.splice(this.tags.indexOf(item), 1)
          }
        }
      })
      if (ischeck && !ischecked) {
        // 全选 && 未被选择  添加当前项
        this.tags.push({ Id: row.Id, Name: row.Name, Type: 2 })
      }
    },
    // 选择所有
    handleSelectAll(selection) {
      var checkall = selection.length > 0
      this.tableData.forEach(item => {
        var ischecked = false // 是否已选择
        this.tags.forEach(citem => {
          if (item.Id === citem.Id) {
            ischecked = true
            if (!checkall) {
              // 取消全选 移除当前tableData中的项
              this.tags.splice(this.tags.indexOf(citem), 1)
            }
          }
        })
        if (checkall && !ischecked) {
          // 全选 && 未被选择 添加当前tableData中的项
          this.tags.push({ Id: item.Id, Name: item.Name, Type: 2 })
        }
      })
    },
    // 点击选择人员的部门树
    handleNodePersonClick(data) {
      if (data.Id === data.UnitId) {
        this.getuserlist()
      } else {
        this.getuserlist(data.Id)
      }
    },
    // 人员名称过滤
    personfillter() {
      GetUserByName(this.searchPersonContent).then(res => {
        this.tableData = res.Data
        this.setChecked()
      })
    },

    /** 角色 */
    getRoleTree() {
      var _this = this
      getUnitRoles().then(res => {
        _this.roles = res.Data
        _this.$nextTick(() => {
          if (this.tags.length > 0 && this.tableData.length > 0) {
            this.roles.forEach(item => {
              var ischeck = false
              this.tags.forEach(citem => {
                if (item.Id === citem.Id) {
                  ischeck = true
                }
              })
              this.$refs.roleref.toggleRowSelection(item, ischeck)
            })
          }
        })
      })
    },
    // 点击的checkbox
    checkdepartmentchoose(data, ischose, leaf) {
      if (ischose) {
        var check = true
        this.tags.forEach(tag => {
          if (tag.Id === data.Id) {
            check = false
          }
        })
        if (check) {
          this.tags.push({ Id: data.Id, Name: data.OrgName, Type: 1 })
        }
      } else {
        for (var i = 0; i < this.tags.length; i++) {
          if (this.tags[i].Id === data.Id) {
            this.tags.splice(i, 1)
          }
        }
      }
    },
    // 过滤部门树
    filterNode(value, data) {
      if (!value) return true
      return data.Name.indexOf(value) !== -1
    },
    // // 点击的checkbox
    // ckeckRoleChoose(data, ischose, leaf) {
    //   if (ischose) {
    //     var check = true
    //     this.tags.forEach(tag => {
    //       if (tag.Id === data.Id) {
    //         check = false
    //       }
    //     })
    //     if (check) {
    //       this.tags.push({ Id: data.Id, Name: data.Name, Type: data.Type })
    //     }
    //   } else {
    //     for (var i = 0; i < this.tags.length; i++) {
    //       if (this.tags[i].Id === data.Id) {
    //         this.tags.splice(i, 1)
    //       }
    //     }
    //   }
    // },
    // // 过滤角色树
    // filterRoleNode(value, data) {
    //   if (!value) return true
    //   return data.Name.indexOf(value) !== -1
    // },
    // 打开弹窗
    showSelectAllInOneDialog() {
      this.selectAllDialogVisible = true

      this.tags = deepClone(this.echoList)

      this.getdepartment()
      this.getuserlist()
      this.getRoleTree()
      // 等待dom全部加载再渲染
      this.$nextTick(() => {
        var arr = []
        for (var i = 0; i < this.tags.length; i++) {
          if (this.tags[i].Type === 1) {
            arr.push(this.tags[i].Id)
            this.$refs.treeref.setCheckedKeys(arr)
          }
        }
      })
    },

    handleClick(tab, event) {},
    handleRoleRow(row) {
      this.$refs.roleref.toggleRowSelection(row)
      // var ischeck = this.selectArr.indexOf(row) > -1 // 是否选中
      var ischecked = false // 是否已选择
      this.tags.forEach(item => {
        if (item.Id === row.Id) {
          ischecked = true
          // 取消选中
          this.tags.splice(this.tags.indexOf(item), 1)
        }
      })
      if (!ischecked) {
        // 全选 && 未被选择  添加当前项
        this.tags.push({ Id: row.Id, Name: row.Name, Type: 3 })
      }
    },
    handleRoleSelect(selection, row) {
      var ischeck = selection.indexOf(row) > -1 // 是否选中
      var ischecked = false // 是否已选择
      this.tags.forEach(item => {
        if (item.Id === row.Id) {
          ischecked = true
          if (!ischeck) {
            this.tags.splice(this.tags.indexOf(item), 1)
          }
        }
      })
      if (ischeck && !ischecked) {
        // 全选 && 未被选择  添加当前项
        this.tags.push({ Id: row.Id, Name: row.Name, Type: 3 })
      }
    },
    // 选择所有
    handleRoleSelectAll(selection) {
      var checkall = selection.length > 0
      this.roles.forEach(item => {
        var ischecked = false // 是否已选择
        this.tags.forEach(citem => {
          if (item.Id === citem.Id) {
            ischecked = true
            if (!checkall) {
              this.tags.splice(this.tags.indexOf(citem), 1)
            }
          }
        })
        if (checkall && !ischecked) {
          this.tags.push({ Id: item.Id, Name: item.Name, Type: 3 })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__body {
  padding-top: 20px;
}
</style>
